{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}

module Handler.MasterCatalog.Object
 ( getObjects
 ) where

import Handler.Types                   ( Star(..), Ra, Dec, Mag )

import Yesod.Persist                   ( runDB )
import Database.Persist.Base           ( PersistValue(..) )
import Database.Persist.GenericSql.Raw ( withStmt )

import Control.Applicative             ( (<$>) )

getObjects f (ra,dec,r) = do
 runDB $ withStmt sql params (withPopper f)

 where
    sql    = "SELECT * FROM master_catalog WHERE mag <= 16 AND q3c_radial_query(ra, dec, ?, ?, ?) ORDER BY mag ASC LIMIT 1000"
    params = PersistDouble <$> [ra,dec,r]

withPopper f popper = loop where
  loop = do
    mrow <- popper
    case mrow of
      Nothing -> return []
      Just (x:y:z:_) -> do
        let (PersistDouble  ra) = x
            (PersistDouble dec) = y
            (PersistDouble mag) = z
            obj = Star ra dec mag
        case f obj of
          True -> do
            xs <- loop
            return (obj:xs)
          False -> loop
